package com.sun.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sun.common.MsResult;
import com.sun.pojo.PmsProductCategory;
import com.sun.service.IPmsProductCategoryService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.util.List;

/**
 * <p>
 * 产品分类 前端控制器
 * </p>
 *
 * @author 妙妙屋
 * @since 2021-12-27
 */
@RestController
@RequestMapping("/productCategory")
public class PmsProductCategoryController {
    @Autowired
    private IPmsProductCategoryService pmsProductCategoryService;

    @GetMapping("/list/withChildren")
    public MsResult listWithCHildren(){
        List<PmsProductCategory> list = pmsProductCategoryService.listChildren();
        return MsResult.isOkData(list);
    }

    @ApiOperation("查询指定级别的商品分类")
    @GetMapping("/list/{parentId}")
    public MsResult listByParentId(@PathVariable Long parentId,String pageSize,String pageNum ){
        Page page= pmsProductCategoryService.list(parentId,pageSize,pageNum);
        return MsResult.isOkDataPage(page);
    }

    @ApiOperation("添加商品分类")
    @PostMapping("/create")
    public MsResult create(@RequestBody PmsProductCategory pmsProductCategory){
        //设置级别
        if(pmsProductCategory.getParentId()==0){
            pmsProductCategory.setLevel(0);
        }else{
            pmsProductCategory.setLevel(1);
        }
        //初始值设置为0
        pmsProductCategory.setProductCount(0);

        pmsProductCategoryService.save(pmsProductCategory);

        System.out.println(pmsProductCategory.getId());
        Long[] idList = pmsProductCategory.getProductAttributeIdList();
        if(idList.length>0){
            for (Long id : idList) {
                pmsProductCategoryService.addRelation(pmsProductCategory.getId(),id);
            }
        }
        //添加商品分类成功之后，还要维护中间表
        // insert into pms_product_category_attribute_relation(product_category_id,product_attribute_id)
        // values (52,24),(52,37),(52,38)

        return MsResult.isOkMessage("添加成功");
    }
}

